package com.chainyoung.common.appcommon.hdwallet;

import android.content.Context;
import android.text.TextUtils;

import com.chainyoung.common.appcommon.entity.HdWallet;
import com.chainyoung.common.bean.UserInfo;
import com.chainyoung.common.constant.LibConstant;
import com.chainyoung.common.utils.SPUtil;
import com.chainyoung.common.utils.StringUtil;
import com.chainyoung.common.appcommon.entity.HdWallets;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONException;
import org.web3j.crypto.CipherException;
import org.web3j.crypto.Credentials;
import org.web3j.crypto.WalletUtils;

import java.io.File;
import java.io.IOException;

public class WalletStoreManger {

    private static Gson gson = new Gson();

    /**
     * 获取用户钱包
     *
     * @return
     */
    public static HdWallets getHdWallets() {
        String str = SPUtil.getInstance().getString(LibConstant.HD_WALLETS, null);
        if (!StringUtil.isEmpty(str)) {
            HdWallets hdWallets = gson.fromJson(str, new TypeToken<HdWallets>() {
            }.getType());
            return hdWallets;
        }
        return null;
    }

    /**
     * 保存钱包信息
     *
     * @param hdWallets
     */
    public static void setHdWallets(HdWallets hdWallets) {
        if (hdWallets != null) {
            String json = gson.toJson(hdWallets);
            SPUtil.getInstance().put(LibConstant.HD_WALLETS, json);
        } else {
            SPUtil.getInstance().put(LibConstant.HD_WALLETS, StringUtil.EMPTY);
        }

    }


    public static Credentials getFullWallet(String password, String walletFilePath) throws IOException, JSONException, CipherException {
//        if (wallet.startsWith("0x"))
//            wallet = wallet.substring(2, wallet.length());
        return WalletUtils.loadCredentials(password, new File(walletFilePath));
    }

}
